package io.renren.modules.job.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.enums.CommonProcessStatus;
import io.renren.modules.customer.entity.MessageRequestEntity;
import io.renren.modules.customer.service.MessageRequestService;
import io.renren.thirdparty.sms.SmsApiClient;
import io.renren.thirdparty.sms.domain.QueryResponse;
import io.renren.thirdparty.sms.domain.QueryResultItem;
import io.renren.thirdparty.sms.enums.RequestStatusType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author sean
 * @since 2020-03-22
 *
 * 查询短信的发送状态
 */
@Component("smsSendingReportQueryTask")
public class SmsSendingReportQueryTask implements ITask {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsSendingReportQueryTask.class);

    @Autowired
    protected SmsApiClient smsApiClient;

    @Autowired
    protected MessageRequestService messageRequestService;

    @Autowired
    protected ObjectMapper objectMapper;

    @Override
    public void run(String params) {
        //获得状态报告
        QueryResponse queryResponse = null;
        try {
            queryResponse = this.smsApiClient.report();
        } catch (Exception e) {
            LOGGER.error("Fail to get sending report due to exception found");
            LOGGER.error(e.getMessage(), e);
        }
        if (queryResponse != null && queryResponse.getStatus() == RequestStatusType.SUCCESS) {
            LOGGER.info("Current balance is {}", queryResponse.getBalance());
            this.updateSendingReport(queryResponse.getItems());
        } else {
            LOGGER.error("Fail to get report data from vendor due to {} ", queryResponse == null || queryResponse.getStatus() == null ? "未知错误" : queryResponse.getStatus().getDescription());
        }
    }

    /**
     * 更新发送状态
     * @param items
     */
    private void updateSendingReport(List<QueryResultItem> items) {
        if (items != null && items.size() > 0) {
            for (QueryResultItem item : items) {
                //仅对状态报告生效
                if (item != null && item.getIsStatusReport()) {
                    MessageRequestEntity entity = this.messageRequestService.getByVendorMessageIdAndPhone(item.getMessageId(), item.getMobile());
                    //找到对应的请求实体
                    if (entity != null) {
                        LOGGER.debug("Fount message entity with id {} by message id {} & mobile phone {}", entity.getId(), item.getMessageId(), item.getMobile());
                        this.updateStatusReport(entity, item);
                    }
                }
            }
        }
    }

    protected void updateStatusReport(MessageRequestEntity entity, QueryResultItem item) {
        CommonProcessStatus targetStatus = null;
        if (QueryResultItem.STAT_DELIVERED.equalsIgnoreCase(item.getStat())) {
            //投递成功
            if (entity.getRequestStatus() == CommonProcessStatus.PROCESSING || entity.getRequestStatus() == CommonProcessStatus.FAIL) {
                targetStatus = CommonProcessStatus.SUCCESS;
            }
        } else {
            //投递失败
            if (entity.getRequestStatus() != CommonProcessStatus.FAIL) {
                targetStatus = CommonProcessStatus.FAIL;
            }
        }
        if (targetStatus != null) {
            entity.setRequestStatus(targetStatus);
            String responseContent = null;
            try {
                responseContent = this.objectMapper.writeValueAsString(item);
            } catch (Exception e) {
                LOGGER.error("Fail to write value as json", e);
                responseContent = item.toString();
            }
            entity.setResponseContent(responseContent);
            this.messageRequestService.updateById(entity);
        }
    }
}
